<template>
	<view class="container">
		<cu-custom bgColor="bg-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">点位绑定NFC</block>
		</cu-custom>

		<view class="bg-top bg-blue">
			<view class="top-box shadow">
				<view class="qh-pic cu-avatar xl" :style="'background-image:url('+logo+')'"></view>
				<view class="qh-title text-bold text-blue text-xl">
					<text>两步绑定NFC</text>
				</view>
				<view class="cu-list menu">

					<view class="cu-item" style="padding: 0;">
						<view class="content">
							<text class="text-black">1.扫描点位二维码</text>
						</view>
						<view class="action">
							<view :class="isScan==true?'bg-green':'bg-red'" class="cu-tag round light">{{isScan==true?'已扫':'未扫'}}</view>
						</view>
					</view>

					<view class="cu-item" style="padding: 0;">
						<view class="content">
							<text class="text-black">2.手机读取NFC卡</text>
						</view>
						<view class="action">
							<view :class="isNfc==true?'bg-green':'bg-red'" class="cu-tag round light">{{isNfc==true?'已读':'未读'}}</view>
						</view>
					</view>
				</view>

			</view>

			<!-- 加入按钮 -->
			<view class="padding-lr flex margin-top-sm" style="justify-content: space-between;">
				<button @click="qrcodeClick" class="cu-btn bg-blue margin-top-sm lg" style="width: 46%;">扫描二维码</button>
				<button @click="qrcodeNfcClick" class="cu-btn bg-red margin-top-sm lg" style="width: 46%;">读取NFC</button>
			</view>

			<view class="center-box shadow">
				<view class="cu-list menu">
					<view class="cu-bar bg-white margin-top-xs u-border-bottom">
						<view class="action sub-title">
							<text class="text-xl text-bold text-blue text-shadow">扫描信息</text>
							<text class="text-ABC text-blue">Result</text>
						</view>
					</view>
					<view class="cu-item" style="padding: 0;">
						<view class="content">
							<text class="cuIcon-myfill text-blue"></text>
							<text class="text-lg">二维码:</text>
						</view>
						<view class="action">
							<text class="text-grey text-sm">{{scanData}}</text>
						</view>
					</view>

					<view class="cu-item" style="padding: 0;">
						<view class='content'>
							<text class="cuIcon-mobilefill text-blue"></text>
							<text class='text-lg'>NFCID:</text>
						</view>
						<view class="action">
							<text class="text-grey text-sm">{{NFCData}}</text>
						</view>
					</view>

				</view>
			</view>

			<view class="padding-lr flex margin-top-sm" style="justify-content: space-between;">
				<button @click="UpdateNfc" class="cu-btn bg-green margin-top-sm lg" style="width: 100%;">更新绑定</button>
			</view>
			
			<view class="padding-lr flex margin-top-sm" style="justify-content: space-between;">
				<button @click="RefreshData" class="cu-btn bg-red margin-top-sm lg" style="width: 100%;">清空数据</button>
			</view>
			
			<view class="padding-lr flex margin-top-sm" style="justify-content: space-between;">
				<button @click="CopyData" class="cu-btn bg-cyan margin-top-sm lg" style="width: 100%;">复制数据</button>
			</view>
			
			<view class="padding-lr" style="margin-top: 15rpx; margin-bottom: 30rpx;">
				<text class="text-grey text-sm">{{confirmData}}</text>
			</view>
			
		</view>
	</view>
</template>

<script>
	import request from '@/common/request.js';
	export default {
		data() {
			return {
				logo:this.$request22.baseUrl1+'/Resource/sg/logo.png',
				errCode: {
					13000: '本设备不支持NFC',
					13001: '系统NFC开关未打开',
					13010: '未知错误',
					13019: '用户未授权',
					13021: '已经开始NFC扫描',
					13018: '尝试在未开始NFC扫描时停止NFC扫描',
					13022: '标签已经连接',
					13023: '尝试在未连接标签时断开连接',
					13013: '未扫描到NFC标签',
					13014: '无效的标签技术',
					13015: '从标签上获取对应技术失败',
					13024: '当前标签技术不支持该功能',
					13017: '相关读写操作失败',
					13016: '连接失败'
				},
				adapter: null,
				nfcID:'',
				isScan:false,
				scanData:'',
				isNfc:false,
				NFCData:'',
				params:{},
				confirmData:'击添加按钮更新信息。如有问题，后续可以在web平台解绑NFCID'
			}
		},
		onShow() {
			
		},
		onLoad() {
			
		},
		onReachBottom() {

		},
		methods: {
			CopyData(){
				uni.setClipboardData({
					data: '此NFC已绑定其他点位：'+this.scanData+','+this.NFCData,
					success: function () {
						uni.showToast({ title: '复制成功', icon: 'none' });
				    }
				})
			},
			RefreshData(){
				let that=this
				that.isScan=false
				that.scanData=''
				that.isNfc=false
				that.NFCData=''
			},
			UpdateNfc(){
				uni.showLoading({
					title: '更新中'
				})
				var that = this;
				let opts = {
					url: 'api/UpdateNfc',
					method: 'get'
				};
				that.params.qrcodeId=that.scanData;
				that.params.nfcId=that.NFCData;
				request.httpTokenRequest(opts,that.params).then(res => {
					uni.hideLoading();
					if(res.data.code == 1){
						uni.showToast({ title: '更新成功', icon: 'none', duration: 2000 });
						that.isScan=false
						that.scanData=''
						that.isNfc=false
						that.NFCData=''
					}
					else{
						that.confirmData=res.data.ms;
						uni.showToast({ title: res.data.msg, icon: 'none', duration: 5000 });
					}
				});
			},
			qrcodeClick() {
				uni.showLoading({
					title: '提交中'
				})
				let that = this;
				that.isScan=false
				that.scanData=''
				 
				 // 只允许通过相机扫码
				 uni.scanCode({
					 onlyFromCamera: true,
					 success: function(res) {
						uni.hideLoading();
						that.result2 = res.result;
						let qrcodeId=request.getRequest(res.result,'id')
						 
						that.isScan=true
						that.scanData=qrcodeId
						 
						 
					 },fail() {
					 	uni.hideLoading();
					 }
				 });
			},
			async qrcodeNfcClick(){
				
				this.isNfc=false
				this.NFCData=''
				//如果是新卡要开卡，如果不是直接巡检
				let e=0;
				try {
					uni.showLoading({
					  title: '请靠近 NFC 卡片'
					})
					this.adapter = wx.getNFCAdapter()
					console.log('adapter', this.adapter)
					await this._startDiscovery()
					const discovered = await this._onDiscovered()
					if (e === 0) {
					  await this.NFCread(discovered)
					} else {
					  await this.NFCwrite(discovered)
					}
					await this._shutDown()
					
					this.isNfc=true
					this.NFCData=this.nfcID
				}catch (e) {
					// TODO handle the exception
					console.log('catch-e', e)
						
					await this._shutDown()
						
					const content = this.errCode[e.errCode]
					uni.showToast({
					  title: content || e.errMsg,
					  icon: 'none',
					  duration: 2000
					})
				}
			},
			// 开始监听
			_startDiscovery () {
			  return new Promise((resolve, reject) => {
				this.adapter.startDiscovery({
				  success: e => {
					console.log('开始监听贴卡', e)
					resolve()
				  },
				  fail: error => {
					// console.log('error', error)
					reject(error)
				  }
				})
			  })
			},
			
			// 监听
			_onDiscovered () {
			  return new Promise((resolve, reject) => {
				this.adapter.onDiscovered(
				  (this.onDiscoveredCallback = res => {
					console.log('读到卡片了', res)
					// console.log('卡-id', res.id)
					console.log('卡-id', this.buf2hex(res.id))
					this.nfcID=this.buf2hex(res.id)
					// 调用打卡接口
				
					resolve(res)
				  })
				)
			  })
			},
				
			// 关闭
			_shutDown () {
			  this.adapter.offDiscovered(this.onDiscoveredCallback)
			  console.log('offDiscovered-关闭读')
			  this.adapter.stopDiscovery()
			  console.log('stopDiscovery-结束')
			  uni.hideLoading()
			},
				
			// 读取
			NFCread (res) {
			  return new Promise((resolve, reject) => {
				if (res.messages) {
				  const payload = res.messages[0].records[0].payload
				  console.log('payload', payload)
				
				  const bufToString = this.arrayBufferToString(payload)
				  console.log('bufToString', bufToString)
				} else {
				  console.log('此卡无内容')
				}
				resolve()
			  })
			},
			
			// 写入
			NFCwrite (res) {
			  return new Promise((resolve, reject) => {
				if (res.techs.includes(this.adapter.tech.nfcA)) {
				  console.log('发现' + this.adapter.tech.nfcA + '卡')
				  const nfcA = this.adapter.getNfcA()
				
				  nfcA.connect({
					success: connectRes => {
					  console.log('设备已连接A', connectRes)
				
					  // 将字符串转成 ArrayBuffer 对象
					  const arrayBuffer = this.stringToArrayBuffer('123')
					  console.log('arrayBuffer', arrayBuffer)
				
					  nfcA.transceive({
						data: arrayBuffer,
						success: transceiveRes => {
						  console.log('发送数据成功, 接收数据如下:', transceiveRes)
						  resolve()
						},
						fail: function (transceiveErr) {
						  console.log('发送数据失败', transceiveErr)
						  reject(transceiveErr)
						}
					  })
					},
					fail: function (connectResErr) {
					  console.log('设备联接错误', connectResErr)
					  reject(connectResErr)
					}
				  })
				} else {
				  uni.showToast({
					title: '标题',
					icon: '不支持此NFC卡',
					duration: 2000
				  })
				  resolve()
				}
			  })
			},
				
			// 转16进制字符
			buf2hex (buffer) {
			  return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('')
			},
				
			stringToArrayBuffer (str) {
			  const buf = new ArrayBuffer(str.length)
			  const bufView = new Uint8Array(buf)
			  for (let i = 0, strLen = str.length; i < strLen; i++) {
				bufView[i] = str.charCodeAt(i)
			  }
			  return buf
			},
				
			arrayBufferToString (buffer) {
			  const data = this.buf2hex(buffer)
			  if (data.length % 2) return ''
				
			  let tmp = ''
			  for (let i = 0; i < data.length; i += 2) {
				tmp += '%' + data.charAt(i) + data.charAt(i + 1)
			  }
				
			  return decodeURI(tmp)
			}
		}
	}
</script>
<style lang="scss" scoped>
	.container {
		width: 750rpx;
		color: #333333;

		.bg-top {
			margin-top: -1rpx;
			width: 750rpx;
			height: 220rpx;
			padding-top: 50rpx;
			border-radius: 0 0 20% 20%;

			.top-box {
				width: 700rpx;
				background-color: #FFFFFF;
				margin: 0 auto;
				border-radius: 20rpx;
				padding: 20rpx 30rpx 0rpx;
				position: relative;

				.qh-pic {
					position: absolute;
					right: 64rpx;
					top: -50rpx;
					border-radius: 12rpx;
				}

				.qh-title {
					width: 100%;
					height: 60rpx;
					line-height: 65rpx;
					padding-right: 190rpx;
				}

				.bxBox {
					position: relative;
					display: flex;
					min-height: 100rpx;
					align-items: center;
					font-size: 30rpx;
					line-height: 1.6em;
					flex: 1;

					.bxImg {
						display: inline-block;
						margin-right: 10rpx;
						width: 1.6em;
						text-align: center;
					}
				}

			}
		}

		.center-box {
			color: #333333;
			width: 700rpx;
			background-color: #FFFFFF;
			margin: 0 auto;
			border-radius: 20rpx;
			padding: 0rpx 30rpx 0rpx;
			position: relative;
			margin-top: 20rpx;
		}
	}
</style>
